import json
import time
from functools import reduce
from flask import Blueprint, request, redirect, make_response, Response, jsonify

from application.models.model import Course, Tags, course_tag, user_course_chapter, CourseComment, Tcourse, \
    user_tcourse_course
from cache import my_cache
from db_init import db
from my_config import LIMIT, CAR_KEY
from swaager_init import siwa
from sqlalchemy import text
from flask_login import current_user, login_required

from tools.data_tools import orm2dict, ret_route, limit_offset

tcourse_blue = siwa.blueprint("tcourse", __name__)


@tcourse_blue.route("/", methods=['GET'])
def tcourse_list():
    end_id = int(request.args.get('end_id', 0))
    data = Tcourse.query.filter(Tcourse.online == 1, Tcourse.id.__gt__(end_id)).limit(LIMIT).all()
    return ret_route(data=orm2dict(data))


@tcourse_blue.route("/<int:tcourse_id>", methods=['GET'])
def tcourse_info(tcourse_id):
    tcourse = Tcourse.query.get(tcourse_id)
    data = orm2dict(tcourse)
    courses = orm2dict(tcourse.courses)
    data['courses'] = courses
    data['teacher'] = orm2dict(tcourse.teacher, filter=['password'])
    try:
        user_course = db.session.query(user_tcourse_course) \
            .filter(user_tcourse_course.c.user_id == current_user.id,
                    user_tcourse_course.c.tcourse_id == tcourse_id) \
            .all()
        data['user_course'] = [i[0] for i in user_course]

    except AttributeError as e:
        data['user_course'] = []
    return ret_route(data=data)


@tcourse_blue.route("/<int:tcourse_id>/comment", methods=['GET'])
def tcourse_comment(course_id):
    course = Course.query.get(course_id)
    comments_dict = {comment.id: orm2dict(comment) for comment in course.comments}
    comments = []

    # for comment in comments_dict.values():
    #     # 根评论 添加到最终字典里
    #     if not comment['reply_id']:
    #         comments.append(comment)
    #         continue
    #
    #     # 找到子评论的 父级评论
    #     if not comments_dict[comment['reply_id']].get('son', None):
    #         comments_dict[comment['reply_id']]['son'] = []
    #
    #     comments_dict[comment['reply_id']]['son'].append(comment)

    for comment in comments_dict.values():
        # 根评论 添加到最终字典里
        if not comment['root_id']:
            comment['son'] = []
            comments.append(comment)
            continue

        # 自己修改表结构
        作者 = CourseComment.query.get(comment['reply_id']).zuozhe
        comment['to_user_id'] = 作者.id
        comment['to_user_name'] = 作者.nikename
        comments_dict[comment['root_id']]['son'].append(comment)

    return ret_route(data=comments)


@tcourse_blue.route("/car/<int:tcourse_id>", methods=['POST'])
@login_required
def tcourse_car(tcourse_id):
    tcourse = Tcourse.query.get(tcourse_id)
    zhe = 1
    for role in current_user.role:
        zhe *= role.zhe
    price = tcourse.price * zhe
    user_bean_price = current_user.bean // 100
    if user_bean_price > price:
        price = 0
        current_user.bean = (user_bean_price - price) * 100 + current_user.bean % 100
    else:
        current_user.bean = current_user.bean % 100
        price -= user_bean_price

    info = {**orm2dict(tcourse, filter=['online']), 'price':price}

    my_cache.hmset(f'{CAR_KEY}{current_user.id}', {int(time.time()): json.dumps(info)})
    db.session.commit()
    return ret_route(data=orm2dict(tcourse))


@tcourse_blue.route("/car", methods=['GET'])
@login_required
def get_tcourse_car():

    car_data = my_cache.hgetall(f'{CAR_KEY}{current_user.id}')

    return ret_route(data=car_data)